<template>
  <VueQrcode
    :value="value"
    :options="{
      width: size,
      errorCorrectionLevel: 'Q',
      color: {
        dark: color
        // light: '#7fdbff',
      }
    }"
    @ready="onReady"
  />
</template>

<script lang="ts">
export default {
  name: 'jc-qrcode'
}
</script>

<script lang="ts" setup>
import VueQrcode from '@chenfengyuan/vue-qrcode'

const props = defineProps({
  value: {
    type: String,
    default: 'https://blog.csdn.net/qq_28550263?spm=1011.2415.3001.5343'
  },
  color: {
    type: String,
    default: '#0074d9'
  },
  size: {
    type: Number,
    default: 200
  },
  coverage: {
    type: Number,
    default: 0.25
  },
  imgSrc: {
    type: String,
    default: ''
  }
})

const drawImage = (
  context: {
    shadowOffsetX: number
    shadowOffsetY: number
    shadowBlur: number
    shadowColor: string
    lineWidth: number
    beginPath: () => void
    moveTo: (arg0: any, arg1: any) => void
    arcTo: (arg0: any, arg1: any, arg2: any, arg3: any, arg4: number) => void
    closePath: () => void
    strokeStyle: string
    stroke: () => void
    clip: () => void
    fillStyle: string
    fillRect: (arg0: any, arg1: any, arg2: any, arg3: any) => void
    drawImage: (arg0: any, arg1: any, arg2: any, arg3: any, arg4: any) => void
  },
  image: HTMLImageElement,
  x: number,
  y: number,
  width: number,
  height: number,
  radius = 4
) => {
  context.shadowOffsetX = 0
  context.shadowOffsetY = 2
  context.shadowBlur = 4
  context.shadowColor = '#00000040'
  context.lineWidth = 8
  context.beginPath()
  context.moveTo(x + radius, y)
  context.arcTo(x + width, y, x + width, y + height, radius)
  context.arcTo(x + width, y + height, x, y + height, radius)
  context.arcTo(x, y + height, x, y, radius)
  context.arcTo(x, y, x + width, y, radius)
  context.closePath()
  context.strokeStyle = '#fff'
  context.fillStyle = '#fff'
  context.drawImage(image, x, x, width, height)
}

const onReady = (canvas: { getContext: (arg0: string) => any; width: number }) => {
  const context = canvas.getContext('2d')
  if (props.imgSrc !== '') {
    const image = new Image()
    image.src = props.imgSrc
    image.crossOrigin = 'anonymous'
    image.onload = () => {
      const width = Math.round(canvas.width * props.coverage)
      const x = (canvas.width - width) / 2
      drawImage(context, image, x, x, width, width)
    }
  }
}
</script>
